package com.scrcu.cloud.wechat.home.endpoint.auth.controller;

import com.scrcu.cloud.wechat.home.endpoint.auth.utils.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

@Slf4j
@RestController
@RequestMapping("/")
public class AuthController {

//    @GetMapping("/WW_verify_Doh7fPla5BVZ1Y95.txt")
//    public String getAuth(){
//        return "Doh7fPla5BVZ1Y95";
//    }

    @GetMapping("/{filename:.+}")
    public void fileDownload(HttpServletResponse response, @PathVariable String filename) throws Exception {
        log.info(filename);
//        String path = "D:\\git-scrcu\\gynsh_wechat_back_sofa\\gynsh_wechat_back_sofa\\app\\web\\src\\main\\resources\\static\\"+filename;
//        String resourcePath = this.getClass().getResource("/").getPath();

        String filepath = "/home/gynsh/static/"+filename;

        File file = new File(filepath);
        if (!file.exists()) {
            log.error("当前下载的文件不存在，请检查路径是否正确");
            return;
//            throw new Exception("当前下载的文件不存在，请检查路径是否正确");
        }

        // 将文件写入输入流
        try (InputStream is = new BufferedInputStream(Files.newInputStream(file.toPath()))) {

            // 一次性读取到内存中
            byte[] buffer = new byte[is.available()];
            int read = is.read(buffer);

            // 清空 response
            response.reset();
            response.setCharacterEncoding("UTF-8");

            // Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            // attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());

            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
            outputStream.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
